package com.atguigu.serviceedu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.serviceedu.entity.EduSubject;
import com.atguigu.serviceedu.entity.excel.ExcelSubjectData;
import com.atguigu.serviceedu.entity.subject.OneSubject;
import com.atguigu.serviceedu.entity.subject.TwoSubject;
import com.atguigu.serviceedu.listener.SubjectExcelListener;
import com.atguigu.serviceedu.mapper.EduSubjectMapper;
import com.atguigu.serviceedu.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author JY
 * @since 2021-01-18
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void add(MultipartFile file, EduSubjectService subjectService) {
        try {
            //调用EasyExcel工具实现对excel表格的读取和操作
            InputStream input = file.getInputStream();
            EasyExcel.read(input, ExcelSubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllSubject() {
        //查询所有一级分类(parent_id==0)
        QueryWrapper<EduSubject> oneWrapper = new QueryWrapper<>();
        oneWrapper.eq("parent_id","0");
        List<EduSubject> eduOneSubjects = baseMapper.selectList(oneWrapper);
        //查询所有二级分类(parent_id!=0)
        QueryWrapper<EduSubject> twoWrapper = new QueryWrapper<>();
        twoWrapper.ne("parent_id","0");
        List<EduSubject> eduTwoSubjects = baseMapper.selectList(twoWrapper);

        //最终返回值
        List<OneSubject> list = new ArrayList<>();

        //封装一级分类
        for (EduSubject eduOneSubject : eduOneSubjects) {
            OneSubject oneSubject = new OneSubject();
            //使用BeanUtils工具类直接复制对象
            BeanUtils.copyProperties(eduOneSubject,oneSubject);

            List<TwoSubject> children = new ArrayList<>();
            //封装二级分类
            for (EduSubject eduTwoSubject : eduTwoSubjects) {
                if(eduTwoSubject.getParentId().equals(eduOneSubject.getId())){
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(eduTwoSubject,twoSubject);
                    children.add(twoSubject);
                }
            }
            oneSubject.setChildren(children);

            list.add(oneSubject);
        }

        return list;
    }
}
